package com.pfizer.pfizerExpertForPad;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.pfizer.DB.DataHelper;
import com.pfizer.Entity.UserInfo;
import com.pfizer.XmlContentHandler.SaxReadXml;

/**
 * PfizerExpertForPadActivity--<b>登陸進入系統介面</b>
 * 
 * @author krui
 *@version 2.1 2011/11/27
 * 
 *@see android.view.View.OnClickListener
 * 
 */
public class PfizerExpertForPadActivity extends Activity implements
		OnClickListener, OnKeyListener,OnFocusChangeListener {
	/** Called when the activity is first created. */
	// 定義相關變量

	private DataHelper dbHelper = null;
	pfizerApplication pApplication = null;
	// 自動完成文本框，用於提示用戶
	AutoCompleteTextView actUserId = null;
	EditText etUserPwd = null;
	ImageButton btnLogin = null;
	ImageButton btnExit = null;
	Button btnWeb = null;
	Context mContext = null;
	UserInfo userinfo = null;
	String strUserId = "";
	String strUserPwd = "";
	int iClickCount = 0;
	String[] Items = { "12345" };

	InputMethodManager m = null;

	// 定義主程式中事物處理程式
	private Handler handler;
	ProgressDialog progressDialog = null;
	boolean isConfirm = false;
	private String UserInfoUrlFormat = "%s/PENS_CRC/Query.aspx?Switch=UserLogin&UserID=%s&UserPass=%s&Obj_From=%s&Obj_ID=%s&ProveCode=%s";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// pApplication.setDataSyncing(false);
		mContext = PfizerExpertForPadActivity.this;
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork() // or
				// .detectAll()
				// for
				// all
				// detectable
				// problems
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());
		InitApp initApp = new InitApp(mContext);
		initApp.SetApp(0);
		pApplication = (pfizerApplication) getApplicationContext();
		dbHelper = pApplication.getDataHelper();
		pApplication.setDataSyncing(false);
		pApplication.setDownloadFlag(false);
		// 當程序啟動時，會先同步數據，如果數據未同步完成，無法進行進一步操作
		//Date dt = new Date();
		//dbHelper.setLoopCount(0, dt.getTime());
		//DataSyncAlarm.setDataSyncAlarm(mContext, true, dt.getTime() + 20 * 1000);

		View v1 = findViewById(R.id.btn1);
		v1.setOnClickListener(this);
		View v2 = findViewById(R.id.btn2);
		v2.setOnClickListener(this);
		View v3 = findViewById(R.id.btn3);
		v3.setOnClickListener(this);
		View v4 = findViewById(R.id.btn4);
		v4.setOnClickListener(this);
		// 先从数据库中取出所有存储过的用户ID，填充USERID输入框的数据适配器
		List<UserInfo> userList = dbHelper.getUserList();
		List<String> items = new ArrayList<String>();
		if (!userList.isEmpty()) {
			for (UserInfo u : userList) {
				items.add(u.getUserID());
			}
			int size = userList.size();
			Items = items.toArray(new String[size]);// 得到数据源
		}
		// 设置USERID输入框的数据适配器
		actUserId = (AutoCompleteTextView) findViewById(R.id.actUserName);
		actUserId.setOnKeyListener(this);
		actUserId.setOnFocusChangeListener(this);
		etUserPwd = (EditText) findViewById(R.id.etUserPwd);
		etUserPwd.setOnKeyListener(this);
		etUserPwd.setOnFocusChangeListener(this);
		btnLogin = (ImageButton) findViewById(R.id.btnLogin);
		btnWeb=(Button)this.findViewById(R.id.btnWeb);
		btnExit = (ImageButton) findViewById(R.id.btnExit);
		actUserId.setAdapter(new ArrayAdapter<String>(mContext,
				android.R.layout.simple_dropdown_item_1line, Items));
		if (actUserId.isFocused()) {
			Editable editable = actUserId.getText();
			Selection.setSelection(editable, editable.length());// 设置光标位置
		}
		userinfo = dbHelper.getLastLoginUser();
		if (userinfo != null && userinfo.getUserID().length() > 0) {
			actUserId.setText(userinfo.getUserID());// 设置最后一次登陆用户
			etUserPwd.requestFocus();
			etUserPwd.setSelection(0, etUserPwd.getText().toString().length());
		} else {
			etUserPwd.clearFocus();
		}
		actUserId.dismissDropDown();
		actUserId.setThreshold(100);// 这里修改Threshold的值是为了防止下次进入的时候下拉框弹出
		actUserId.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				actUserId.setThreshold(2);// 改回正常值
			}
		});
		// 确认按钮监听器
		btnLogin.setOnClickListener(this);
		btnWeb.setOnClickListener(this);
		// 退出按钮监听器
		btnExit.setOnClickListener(this);

		handler = new Handler() {
			@Override
			// 處理程式
			public void handleMessage(Message msg) {
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				try {
					switch (msg.what) {
					case 2:
						Toast.makeText(mContext, "驗證超時!", 1).show();

						break;
					case 1:
						Toast.makeText(mContext, "驗證成功!", 1).show();
						String userId = msg.getData().getString("UserId");
						pApplication.setUserID(userId);
						Intent intent = new Intent(mContext,
								PunchCardActivity.class);
						startActivity(intent);
						finish();
						break;
					case -1:
						// 單個文件下載失敗
						Toast.makeText(mContext, "連接服務器失敗!", 1).show();
						break;
					case -2:
						Toast.makeText(mContext, "獲取用戶信息失敗!", 1).show();
						break;
					}
				} catch (Exception ex) {
					Toast.makeText(mContext, "異常終止！!", 1).show();
				}
				super.handleMessage(msg);
			}
		};

	}

	@Override
	// 监听退出键
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			new AlertDialog.Builder(mContext).setTitle("離開程式").setMessage(
					"確定離開嗎？").setPositiveButton("確定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

							Date dt = new Date();
							dbHelper.setLoopCount(0, dt.getTime());
							DataSyncAlarm.setDataSyncAlarm(mContext, true, dt
									.getTime() + 10 * 1000);
							pApplication.setUserID("");
							pApplication.setUserName("");
							finish();
						}
					}).setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					}).show();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int Id = v.getId();
		switch (Id) {
		case R.id.btnWeb:
			 //Uri uri = Uri.parse("http://www.baidu.com");
			 Uri uri = Uri.parse(pApplication.getWebUrl());
			 Intent intentUri = new Intent(Intent.ACTION_VIEW, uri);
			 startActivity(intentUri);
			break;
		case R.id.btnLogin:
			UserLogin();
			break;
		case R.id.btnExit:
			new AlertDialog.Builder(mContext).setTitle("離開程式").setMessage(
					"確定離開嗎？").setPositiveButton("確定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

							Date dt = new Date();
							dbHelper.setLoopCount(0, dt.getTime());
							DataSyncAlarm.setDataSyncAlarm(mContext, true, dt
									.getTime() + 10 * 1000);
							pApplication.setUserID("");
							pApplication.setUserName("");
							finish();
						}
					}).setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					}).show();
			break;
		case R.id.btn1:
			if (iClickCount == 0) {
				iClickCount = 1;
			} else {
				iClickCount = 0;
			}
			break;
		case R.id.btn2:
			if (iClickCount == 1) {
				iClickCount = 2;
			} else {
				iClickCount = 0;
			}
			break;
		case R.id.btn3:
			if (iClickCount == 2) {
				iClickCount = 3;
			} else {
				iClickCount = 0;
			}
			break;
		case R.id.btn4:
			if (iClickCount == 3) {
				Intent intent = new Intent(mContext, ActivitySetting.class);
				startActivity(intent);
			} else {
				iClickCount = 0;
			}
			break;
		}
	}

	private void UserLogin() {
		// TODO Auto-generated method stub
		strUserId = actUserId.getText().toString();
		strUserPwd = etUserPwd.getText().toString();
		if (strUserId.equals("") && strUserPwd.equals("")) {
			Toast.makeText(mContext, "請輸入帳號和密碼！", Toast.LENGTH_SHORT).show();
			return;
		} else if (strUserId.equals("")) {
			Toast.makeText(mContext, "請輸入帳號！", Toast.LENGTH_SHORT).show();
			return;
		} else if (strUserPwd.equals("")) {
			Toast.makeText(mContext, "請輸入密碼！", Toast.LENGTH_SHORT).show();
			return;
		} else {
			userinfo = new UserInfo();
			userinfo.setUserID(strUserId);
			userinfo.setUserPsw(strUserPwd);
			if (!dbHelper.HaveUserInfo(userinfo.getUserID())) {
				// 如果数据库中没有此ID，就跟服务器交互认证，认证成功后存入本地数据库
				//
				progressDialog = ProgressDialog.show(mContext, null, "驗證中...",
						true, true);
				try {

					new Thread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							String urlStr = String.format(UserInfoUrlFormat,
									pApplication.getWebUrl(), userinfo
											.getUserID(),
									userinfo.getUserPsw(), pApplication
											.getObjFrom(), pApplication
											.getObjID(), pApplication
											.getUserLoginProveCode());
							InputStream inputStream = null;
							try {
								URL url = new URL(urlStr);
								// inputStream = url.openStream();
								HttpURLConnection urlCon = (HttpURLConnection) url
										.openConnection();
								urlCon.setConnectTimeout(10 * 1000);
								urlCon.setReadTimeout(10 * 1000);
								int responseCode = urlCon.getResponseCode();
								if (responseCode == HttpURLConnection.HTTP_OK) {
									inputStream = urlCon.getInputStream();
								}
							} catch (IOException e) {
								// TODO: handle exception
								Message msg = new Message();
								msg.what = -1;
								msg.getData().putString("error", "連接服務器失敗!");
								handler.sendMessage(msg);
								return;
							}

							try {
								List<UserInfo> userInfoList = SaxReadXml
										.readUserInfo(inputStream);
								if (!userInfoList.isEmpty()) {// 如果解析后的user信息非空
									userinfo.setUserName(userInfoList.get(0)
											.getUserName());// 将从网络上获取的user信息存到javabean
									userinfo.setUserEmail(userInfoList.get(0)
											.getUserEMail());
									pApplication
											.setUserID(userinfo.getUserID());
									pApplication.setUserName(userinfo
											.getUserName());
									Date date = new Date();
									String currentTime = date.toGMTString();// 得到打卡时间
									userinfo.setLoginTime(currentTime);
									dbHelper.SaveUserInfo(userinfo);// 存入本地数据库
									Message msg = new Message();
									msg.what = 1;
									Bundle b = new Bundle();
									b.putString("UserId", userinfo.getUserID());
									msg.setData(b);
									msg.getData().putString("error", "驗證成功！");
									handler.sendMessage(msg);
								} else {
									Message msg = new Message();
									msg.what = -2;
									msg.getData().putString("error",
											"獲取用戶信息失敗！");
									handler.sendMessage(msg);
								}
							} catch (Exception e) {
								// TODO: handle exception
								Message msg = new Message();
								msg.what = -2;
								msg.getData()
										.putString("error", e.getMessage());
								handler.sendMessage(msg);
								return;
							}
						}
					}).start();
				} catch (Exception ex) {
					// Toast.makeText(mContext,
					// ex.getMessage(),Toast.LENGTH_SHORT).show();
					return;
				}
			} else {// 如果数据库中有此用户，离线登陆
				// 如果密码正确，直接进入打卡页面
				if (dbHelper.UserPswTest(userinfo)) {
					UserInfo user = dbHelper.getUserByUserId(userinfo
							.getUserID());
					Intent intent = new Intent(mContext,
							PunchCardActivity.class);
					pApplication.setUserID(strUserId);
					pApplication.setUserName(user.getUserName());
					startActivity(intent);
					Date date = new Date();
					String currentTime = date.toGMTString();
					userinfo.setLoginTime(currentTime);
					dbHelper.UpdateUserInfo(userinfo);// 更新数据

				} else {
					Toast.makeText(mContext, "密碼錯誤，請重新輸入！", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				((Activity) mContext).finish();// 銷毀
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		dbHelper = null;
		pApplication = null;
		actUserId = null;
		etUserPwd = null;
		btnLogin = null;
		btnExit = null;
		mContext = null;
		userinfo = null;
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// int i=event.getAction();
		if (keyCode == 66 && event.getAction() == KeyEvent.ACTION_UP) {
			int Id = v.getId();
			switch (Id) {
			case R.id.actUserName:
				etUserPwd.requestFocus();
				etUserPwd.setSelection(0, etUserPwd.getText().toString()
						.length());
				// etUserPwd.setSelection(0, etUserPwd.getText().length());
				break;
			case R.id.etUserPwd:
				m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				UserLogin();
				// etUserPwd.setInputType(InputType.TYPE_NULL);
				break;
			default:
				break;
			}
			return true;
		} else if (keyCode == 66 && event.getAction() == KeyEvent.ACTION_DOWN) {
			return true;
		}
		return false;
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		EditText _v=(EditText)v;
        if (!hasFocus) {// 落空核心
            _v.setHint(_v.getTag().toString());
        } else {
            String hint=_v.getHint().toString();
            _v.setTag(hint);
            _v.setHint("");
        }

	}

}